import { Routes, Route, useNavigate } from 'react-router-dom';
import Navigation from './Navigation';
import SelectFile from './SelectFile';
import Conversation from './conversation/Conversation';
import About from './About';
import LoginPage from './login/Login'; 
import PageNotFound from './PageNotFound';
import { inject } from '@vercel/analytics';
import { useMediaQuery } from './hooks';
import { useEffect, useState } from 'react';
import Setting from './Setting';
import Prompt  from './prompt/prompt';
import AiEditCustom from './AIedit/aiedit';
import Audit from './Audit/audit';
import AuditTimeLine from './components/AuditTimeline'

inject({
   debug: true,
   mode: 'development',
});

export default function App() {
  const { isMobile } = useMediaQuery();
  const [navOpen, setNavOpen] = useState(!isMobile);
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const navigate = useNavigate();

  useEffect(() => {
    // 假设当sessionStorage中有access_token时表示用户已登录
    const token = sessionStorage.getItem('access_token');

    setIsLoggedIn(!!token);

    // 如果未登录，则重定向到登录页面
    if (!token) { 
      setIsLoggedIn(false);
      navigate('/');
    }
  }, [navigate]);

  const handleLogout = () => {
    sessionStorage.removeItem('access_token');
    setIsLoggedIn(false);
    navigate('/');
  };

  return (
    <div className="min-h-full min-w-full dark:bg-raisin-black">
      {isLoggedIn && (
        <>
          <Navigation navOpen={navOpen} setNavOpen={setNavOpen} />
          {/* 添加退出登录按钮 */}
          <button 
            onClick={handleLogout} 
            className="absolute top-4 right-4 bg-red-500 text-white px-4 py-2 rounded shadow"
          >
            退出登录
          </button>
        </>
      )}
      <div
        className={`transition-all duration-200 ${
          isLoggedIn
            ? !isMobile
              ? `ml-0 ${!navOpen ? '-mt-5 md:mx-auto lg:mx-auto' : 'md:ml-72'}`
              : 'ml-0 md:ml-16'
            : 'ml-0 -mt-5 md:mx-auto lg:mx-auto' 
        }`}
      >
        <Routes>
          <Route path="/" element={<LoginPage />} />
          <Route path="/conversation" element={<Conversation />} /> 
          <Route path="/about" element={<About />} />
          <Route path="*" element={<PageNotFound />} />
          <Route path="/settings" element={<Setting />} /> 
          <Route path="/select-file" element={<SelectFile />} /> 
          <Route path="/prompt" element={<Prompt />} /> 
          <Route path="/aiEditCustom" element={<AiEditCustom />}/>
          <Route path="/audit" element={<Audit />} />
          <Route path="/auditTimeline" element={<AuditTimeLine />} />
        </Routes>
      </div>
    </div>
  );
}